﻿using System.Text;
using Xunit;
using Xunit.Abstractions;

namespace 初级算法.其他
{
    public class 最长公共前缀
    {
        /// <summary>
        /// https://leetcode.cn/problems/longest-common-prefix/
        /// </summary>
        public class Solution
        {
            /// <summary>
            /// 2021-7-7 1:44周三
            /// 执行用时：92 ms, 在所有 C# 提交中击败了100.00%的用户
            /// 内存消耗：24.9 MB, 在所有 C# 提交中击败了37.81%的用户
            /// </summary>
            /// <param name="strs"></param>
            /// <returns></returns>
            public string LongestCommonPrefix(string[] strs)
            {
                StringBuilder sb = new StringBuilder();

                for (int i = 0; i < strs[0].Length; i++)
                {
                    int x = 1;
                    char same = strs[0][i];
                    while (x < strs.Length)
                    {
                        if (i == strs[x].Length || strs[x][i] != same) break;
                        x++;
                    }
                    if (x == strs.Length) sb.Append(same);
                    else break;
                }

                return sb.ToString();
            }
        }


        ITestOutputHelper output;
        public 最长公共前缀(ITestOutputHelper output)
        {
            this.output = output;
        }

        [Fact]
        public void Test1()
        {

            Solution S = new Solution();
            string r;

            r = S.LongestCommonPrefix(new string[] { "flower", "flow", "flight" });
            output.WriteLine("" + r);

            r = S.LongestCommonPrefix(new string[] { "ab", "a", });
            output.WriteLine("" + r);

            r = S.LongestCommonPrefix(new string[] { "aa", "aa", });
            output.WriteLine("" + r);
        }
    }
}
